<template>
    <van-sticky>
        <van-nav-bar
            title="确认订单"
            left-text="返回"
            left-arrow
            @click-left="onBack"
        />
    </van-sticky>

    <!-- 选择收货人 -->
    <van-contact-card type="add" @click="ToAddress" v-if="Object.getOwnPropertyNames(address).length === 0" />
    <van-contact-card type="edit" :name="address.consignee + ' ' + address.address" :tel="address.mobile" @click="ToAddress" v-else />

    <van-card
        v-for="item in CartList"
        :key="item.id"
        :num="item.nums"
        :price="item.total"
        :title="item.products.name"
    >
        <template #thumb>
            <van-image
                width="88px"
                height="88px"
                fit="cover"
                :src="item.products.thumbs_cdn"
            />

        </template>

        <template #desc>
            <div v-if="item.attrs">
                <van-tag plain type="primary" v-for="attr of JSON.parse(item.attrs)">{{ attr.value }}</van-tag>
            </div>
            <van-tag plain type="primary" v-else>{{ item.products.flag_text }}</van-tag>
        </template>

        <template #tags>
            <div>
                单价：￥{{ item.price }}
            </div>
        </template>
    </van-card>

    <van-cell title="支付方式" :value="PayActive.text" is-link @click="PayShow = true" />

    <van-popup v-model:show="PayShow" round position="bottom">
        <van-picker
            :columns="PayList"
            @cancel="PayShow = false"
            @confirm="onPayConfirm"
        />
    </van-popup>

    <!-- 优惠券单元格 -->
    <van-coupon-cell
        :coupons="CouponList"
        :chosen-coupon="CouponActive"
        @click="CouponShow = true"
    />

    <!-- 优惠券列表 -->
    <van-popup
        v-model:show="CouponShow"
        round
        position="bottom"
        style="height: 90%; padding-top: 4px;"
    >
        <van-coupon-list
            :coupons="CouponList"
            :chosen-coupon="CouponActive"
            :exchange-button-disabled="false"
            :show-exchange-bar="false"
            :disabled-coupons="NotCouponList"
            @change="onCouponChange"
        />
    </van-popup>

   <!--订单备注 -->
   <van-field 
        v-model="remark"
        rows="2"
        autosize
        label="订单备注"
        type="textarea"
        maxlength="120"
        placeholder="请输入订单备注"
        show-word-limit
    />

    <van-submit-bar :price="total" button-text="提交订单" @submit="onSubmit" />

</template>

<script setup>
const { proxy } = getCurrentInstance();

const business = proxy.$business;
const cartids = ref(proxy.$route.query.cartids ?? 0);
const CartList = ref([]);
const address = proxy.$address;// 收货人信息
const PayShow = ref(false);// 控制是否显示弹出层
const PayList = ref([
    {text:'余额',value:'money'},
    {text:'支付宝',value:'zfb'},
    {text:'微信',value:'wx'}
]);// 支付方式
const PayActive = ref(PayList.value[0]);// 选择支付方式
const CouponList = ref([]);
const CouponActive = ref(-1);
const CouponShow = ref(false);
const NotCouponList = ref([]);
const remark = ref('');


// 单独购买
const action = ref(proxy.$route.query.action ?? "");
const pronum = ref(proxy.$route.query.pronum ?? 0);
const proid = ref(proxy.$route.query.proid ?? 0);
const relationids = ref(proxy.$route.query.relationids ?? 0);

   

onBeforeMount(() => {
    getCartData();

    if(Object.getOwnPropertyNames(proxy.$address.value).length === 0)
    {
        getDefaultAddress();
    }

    getCouponData();
})

const getCartData = async () =>{
    let params = {};

    if (action.value === "buyone") {
        params = {
            action:action.value,
            busid: business.value.id,
            pronum: pronum.value,
            proid: proid.value,
            relationids: relationids.value,
        };
        
    } else {
        params = {
            busid: business.value.id,
            cartids: cartids.value,
        };
    }
    let result = await proxy.$http.post({
        url:'/order/cart',
        params
    })

    if(result.code === 1)
    {
        CartList.value = result.data;
    }else{
        proxy.$fail({
            message:result.msg,
            // onClose:() => onBack()
        })
    }
}

const getCouponData = async () =>
{
    let params = {
        busid:business.value.id
    }

    let result = await proxy.$http.post({
        url:'/order/coupon',
        params
    })

    if(result.code === 1)
    {
        for(let item of result.data.CouponList)
        {
            CouponList.value.push({
                id:item.id,// 领取优惠券记录id
                name:item.coupon.title,// 优惠券名称
                startAt:item.coupon.createtime,// 优惠券开始时间
                endAt:item.coupon.endtime,// 优惠券结束时间
                rate: item.coupon.rate,// 折扣率
                valueDesc: `${item.coupon.rate*100}`,// 折扣券优惠金额文案
                unitDesc: '折',// 单位文案
                condition:item.coupon.status_text,// 满减条件
            })
        }

        for(let item of result.data.NotCouponList)
        {
            NotCouponList.value.push({
                id:item.id,// 领取优惠券记录id
                name:item.coupon.title,// 优惠券名称
                startAt:item.coupon.createtime,// 优惠券开始时间
                endAt:item.coupon.endtime,// 优惠券结束时间
                rate: item.coupon.rate,// 折扣率
                valueDesc: `${item.coupon.rate*100}`,// 折扣券优惠金额文案
                unitDesc: '折',// 单位文案
                condition:item.coupon.status_text,// 满减条件
            })
        }
    }
}

const getDefaultAddress = async () =>
{
    let params = {
        busid:business.value.id
    }

    let result = await proxy.$http.post({
        url:'/order/address',
        params
    })

    if(result.code === 1)
    {
        address.value = result.data;
    }
}

const onPayConfirm = ({selectedOptions}) =>
{
    let value = selectedOptions[0];

    PayShow.value = false;

    PayActive.value = value;
}

const onCouponChange = (index) =>
{
    CouponActive.value = index;

    CouponShow.value = false;
    
    if(index != -1)
    {
        let coupon = CouponList.value[index];

        let total = 0;
         
        CartList.value.map(item => total += parseFloat(item.total));

        total = total.toFixed(2);

        let rate = coupon.rate ? coupon.rate : 1;

        // 优惠后的总价
        let RatePrice = (parseFloat(total) * parseFloat(rate)).toFixed(2);

        let CouponPrice = (parseFloat(total) - parseFloat(RatePrice)).toFixed(2);
        
        CouponList.value[index].value = parseFloat(CouponPrice) * 100;
       
        
    }
}


const onSubmit = async () =>
{
    let params = {};

    if (action.value === "buyone") {
        params = {
        action:action.value,
        busid:business.value.id,
        addrid:address.value.id,
        pay:PayActive.value.value,
        remark:remark.value,
        proid:proid.value,
        relationids: relationids.value,
        pronum: pronum.value,
        };
        
    } else {
        params = {
        cartids:cartids.value,
        busid:business.value.id,
        addrid:address.value.id,
        pay:PayActive.value.value,
        remark:remark.value
        };
    }
    

    if(CouponActive.value !== -1)
    {
        params.couponid = CouponList.value[CouponActive.value].id;
    }

    let result = await proxy.$http.post({
        url:'/order/add',
        params
    })

    if(result.code === 1)
    {
        proxy.$showSuccessToast({
            message:result.msg,
            onClose:() =>
            {
                proxy.$router.push({path:'/order',replace:true});
            }
        })
    }else{
        proxy.$fail(result.msg);
    }
    
}

const total = computed(() => {
    let total = 0;
    if(CartList.value.length > 0)
    {
        CartList.value.map(item => total += parseFloat(item.total));
    }

    if(CouponActive.value !== -1)
    {
        total *= parseFloat(CouponList.value[CouponActive.value].rate);
    }



    return total * 100;
})

const ToAddress = () => proxy.$router.push({path:'/address',query:{action:'order'}});

const onBack = () => proxy.$router.back();
onBeforeUnmount(() => proxy.$ResetAddress());
</script>